from django.shortcuts import render
from django.http import HttpResponse, JsonResponse
from .models import *
from django.core.serializers import serialize
from django.views.generic import View
from django.views.decorators.cache import cache_page
# Create your views here.


@cache_page(15 * 60)
def index(request):
    """
    跳转到首页
    """
    type_list = Category.objects.all()
    goods_list = Goods.objects.filter(category=Category.objects.get(pk=1))
    context = {"type_list": type_list, "goods_list": goods_list}
    return render(request, "goods/index.html", context)


def get_type_goods(request):
    """
    ajax获取分类商品
    """
    info = request.GET.get("type_name")
    type_obj = Category.objects.get(cname=info)
    goods_list = Goods.objects.filter(category=type_obj)
    goods = goods_list.values("g_name", "price", "desc", "detail__gd_url", "old_price", "category")
    return JsonResponse({"goods": list(goods)})


@cache_page(15 * 60)
def type_goods(request, pcode):
    """
    通过分类ID获取分类商品
    """
    info = Category.objects.get(pk=pcode)
    type_list = Category.objects.all()
    goods = Goods.objects.filter(category=info)
    context = {"goods_list": goods, "type_list": type_list,}
    return render(request, "goods/category.html", context)







